const router = require('../config/router');
const _ = require('lodash');
const jwt = require('jsonwebtoken');
const moment = require('moment');
const secret = require('../config/secret');
function author() {
    /**
     * 验证
     * @type {function(): Function}
     */
    return async (ctx, next) => {
        const url = ctx.request.url;
        const status = _.includes(router, url);
        console.log('请求时间：', moment().format('YYYY-MM-DD HH:mm:ss'));
        // 为了放行硬件，无奈之举
        if (_.includes(url, '/api/ReportStatus')) {
            await next();
        } else if (_.includes(url, '/api/BeginService')) {
            await next();
        } else if (_.includes(url, '/api/FinishService')) {
            await next();
        } else if (!status) {
            let token;
            token = ctx.header.token;
            // 先从头上去获取token，如果没有就去query上获取
            if (!token) {
                token = ctx.request.query.token;
                if (!token) {
                    ctx.set('Content-Type', 'application/json');
                    ctx.body = { code: 2, msg: 'The token was not found' };
                    return;
                }
            }
            // 获取到token后验证
            let data = {};
            let include = _.includes(url, '/api/admin');
            data = verifyToken(token, include);

            if (!data) {
                ctx.body = { code: 2, msg: '信息已经失效' };
                return;
            }
            // 赋值user
            ctx.user = data;
            await next();
        } else {
            await next();
        }
    };
}
/**
 * 验证token
 * @param _token
 * @returns {*}
 */
function verifyToken(_token, status) {
    let secrets = '';

    // 判断类型
    if (status) {
        secrets = secret.admin;
    } else {
        secrets = secret.program;
    }

    let verify = jwt.verify(_token, secrets, (error, decoded) => {
        if (error) {
            return false;
        }
        return decoded;
    });

    return verify;
}
module.exports = author;
